<template>
  <ChartContainer :title="title">
    <div class="chart" ref="chartRef"></div>
    <div class="year-selector" v-if="yearOptions.length > 0">
      <label for="year-select">选择年份:</label>
      <select id="year-select" v-model="selectedYear" @change="updateChartForYear">
        <option v-for="year in yearOptions" :key="year" :value="year">{{ year }}年</option>
      </select>
    </div>
  </ChartContainer>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, toRefs, computed } from 'vue';
import * as echarts from 'echarts';
import ChartContainer from './ChartContainer.vue';
import { getOrdersByYearMonth } from '../../api/auth';

// 定义年月数据类型
interface YearMonthData {
  year: number;
  months: {
    orderCount: number;
    productCount: number;
    salesAmount: number;
  }[];
  totalOrders: number;
  totalProducts: number;
  totalSales: number;
}

defineOptions({
  name: 'LeftBottom'
});

const props = defineProps({
  title: {
    type: String,
    default: '月度营收增长趋势'
  },
  chartData: {
    type: Array,
    default: () => []
  }
});

const { title } = toRefs(props);

const chartRef = ref(null);
let chart: echarts.ECharts | null = null;
const yearMonthData = ref<YearMonthData[]>([]);
const selectedYear = ref<number | null>(null);

// 计算可选的年份选项
const yearOptions = computed(() => {
  return yearMonthData.value.map(item => item.year).sort((a, b) => a - b);
});

// 获取月份名称
const getMonthNames = () => {
  return ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
};

const fetchYearMonthData = async () => {
  try {
    const res = await getOrdersByYearMonth();
    if (res.data && res.data.code === 200 && res.data.data) {
      yearMonthData.value = res.data.data;
      
      // 如果有数据，默认选择最近的一年
      if (yearMonthData.value.length > 0) {
        const years = yearMonthData.value.map(item => item.year);
        selectedYear.value = Math.max(...years);
        updateChartForYear();
      } else {
        initEmptyChart();
    }
    } else {
      initEmptyChart();
    }
  } catch (error) {
    console.error('获取年度月度销售数据失败:', error);
    initEmptyChart();
  }
};

// 更新图表以显示选定年份的数据
const updateChartForYear = () => {
  if (!selectedYear.value) return;
  
  const yearData = yearMonthData.value.find(item => item.year === selectedYear.value);
  if (!yearData) {
    initEmptyChart();
    return;
  }
  
  initChart(yearData);
};

const initEmptyChart = () => {
  if (!chartRef.value) return;
  
  if (!chart) {
  chart = echarts.init(chartRef.value);
  }
  
    chart.setOption({
      title: {
        text: '暂无月度营收数据',
        left: 'center',
        top: 'middle',
        textStyle: {
          color: '#fff',
          fontSize: 16
        }
      }
    });
};

const initChart = (yearData: YearMonthData) => {
  if (!chartRef.value) return;
  
  if (!chart) {
    chart = echarts.init(chartRef.value);
  }
  
  const monthNames = getMonthNames();
  const salesData = yearData.months.map(month => month.salesAmount);
  const orderCounts = yearData.months.map(month => month.orderCount);
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#001a3d'
        },
        lineStyle: {
          color: 'rgba(0, 183, 255, 0.4)',
          width: 1
        }
      },
      backgroundColor: 'rgba(0, 24, 57, 0.9)',
      borderColor: 'rgba(0, 183, 255, 0.4)',
      borderWidth: 1,
      padding: [8, 12],
      textStyle: {
        color: '#ffffff',
        fontSize: 12
      },
      formatter: function(params: any) {
        const monthIndex = params[0].dataIndex;
        const month = monthNames[monthIndex];
        const salesAmount = yearData.months[monthIndex].salesAmount;
        const orderCount = yearData.months[monthIndex].orderCount;
        const productCount = yearData.months[monthIndex].productCount;
        
        return `${selectedYear.value}年${month}<br/>
               <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:#00e3ff;margin-right:5px;"></span>销售额: ¥${salesAmount.toLocaleString()}<br/>
               <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:#ff36a0;margin-right:5px;"></span>订单数: ${orderCount}<br/>
               <span style="display:inline-block;width:10px;height:10px;border-radius:50%;background-color:#ffcc00;margin-right:5px;"></span>商品数: ${productCount}`;
      }
    },
    legend: {
      data: ['销售额', '订单数'],
      textStyle: {
        color: '#fff',
        fontSize: 12
      },
      icon: 'circle',
      itemWidth: 10,
      itemHeight: 10,
      top: 0,
      right: 40,
      itemGap: 40,
      formatter: function(name: string) {
        return name;
      },
      selectedMode: true
    },
    grid: {
      left: '3%',
      right: '10%',
      bottom: '10%',
      top: '25%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: monthNames,
      axisLine: {
        lineStyle: {
          color: 'rgba(131, 146, 165, 0.6)'
        }
      },
      axisLabel: {
        color: '#fff',
        fontSize: 10,
        margin: 12
      },
      axisTick: {
        show: false
      },
      splitLine: {
        show: false
      },
      boundaryGap: false
    },
    yAxis: [
      {
      type: 'value',
        name: '销售额',
        nameTextStyle: {
          color: 'rgba(255,255,255,0.7)',
          padding: [0, 30, 0, 0],
          fontSize: 11
        },
      axisLine: {
          show: false
      },
      splitLine: {
        lineStyle: {
            color: 'rgba(131, 146, 165, 0.2)',
            type: 'dashed'
          }
        },
        axisLabel: {
          color: '#fff',
          formatter: '¥{value}',
          fontSize: 10
        }
      },
      {
        type: 'value',
        name: '订单数',
        nameTextStyle: {
          color: 'rgba(255,255,255,0.7)',
          padding: [0, 0, 0, 30],
          fontSize: 11
        },
        position: 'right',
        axisLine: {
          show: false
        },
        splitLine: {
          show: false
      },
      axisLabel: {
          color: '#fff',
          fontSize: 10
      }
      }
    ],
    series: [
      {
        name: '销售额',
      type: 'line',
        data: salesData,
      smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 6,
        showSymbol: true,
        emphasis: {
          focus: 'series',
          scale: true
        },
      lineStyle: {
        width: 3,
          shadowColor: 'rgba(0, 227, 255, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 10,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#00e3ff' },
              { offset: 1, color: '#5cacff' }
            ]
          }
        },
        itemStyle: {
          color: '#00e3ff',
          borderWidth: 2,
          borderColor: '#ffffff'
        },
      areaStyle: {
          opacity: 0.2,
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(0, 227, 255, 0.6)' },
            { offset: 1, color: 'rgba(1, 18, 71, 0.1)' }
          ])
        },
        z: 2
      },
      {
        name: '订单数',
        type: 'line',
        yAxisIndex: 1,
        data: orderCounts,
        smooth: true,
        symbol: 'emptyCircle',
        symbolSize: 6,
        showSymbol: true,
        emphasis: {
          focus: 'series',
          scale: true
        },
        lineStyle: {
          width: 3,
          shadowColor: 'rgba(255, 54, 160, 0.3)',
          shadowBlur: 10,
          shadowOffsetY: 10,
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#ff36a0' },
              { offset: 1, color: '#ff7589' }
            ]
          }
      },
        itemStyle: {
          color: '#ff36a0',
          borderWidth: 2,
          borderColor: '#ffffff'
      },
        z: 3
      }
    ],
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut' as const
  };
  
  chart.setOption(option);
};

watch(() => props.chartData, () => {
  if (props.chartData && Array.isArray(props.chartData) && props.chartData.length > 0) {
    yearMonthData.value = props.chartData as YearMonthData[];
    
    // 更新默认选择的年份
    if (yearMonthData.value.length > 0) {
      const years = yearMonthData.value.map(item => item.year);
      selectedYear.value = Math.max(...years);
      updateChartForYear();
    }
  }
}, { deep: true });

// 监听窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

onMounted(() => {
  fetchYearMonthData();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
  }
  window.removeEventListener('resize', handleResize);
});

// 添加refresh方法供父组件调用
const refresh = async () => {
  await fetchYearMonthData();
};

// 暴露refresh方法
defineExpose({
  refresh
});
</script> 

<style scoped>
.year-selector {
  position: absolute;
  top: 12px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  display: flex;
  align-items: center;
  gap: 8px;
}

.year-selector label {
  color: #fff;
  font-size: 12px;
}

.year-selector select {
  background-color: rgba(0, 24, 57, 0.7);
  color: #fff;
  border: 1px solid rgba(0, 183, 255, 0.4);
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
  outline: none;
}

.year-selector select option {
  background-color: rgba(0, 24, 57, 0.9);
}

.chart {
  width: 100%;
  height: 280px;
  padding: 10px;
  border-radius: 6px;
  animation: chartFadeIn 0.8s ease-in-out;
  display: block !important;
}

@keyframes chartFadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 增强图表轴线样式 */
.chart path.domain,
.chart .tick line {
  stroke-opacity: 0.3;
  stroke-width: 1px;
}

/* 图表标题样式增强 */
.chart-title {
  margin-bottom: 15px;
  position: relative;
  text-shadow: 0 0 5px rgba(0, 157, 255, 0.7);
  letter-spacing: 1px;
}

.chart-title::after {
  content: '';
  position: absolute;
  bottom: -5px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background: linear-gradient(to right, transparent, rgba(0, 157, 255, 0.8), transparent);
}
</style>